<?php


namespace app\erp\controller;


use app\admin\controller\Base;
use app\admin\model\Admin;
use app\common\model\Users as UsersModel;
use app\common\widget\Widget;
use think\facade\Env;

class Users extends Base
{


    function index(){


        //查询：时间格式过滤 获取格式 2015-11-12 - 2015-11-18
        $sldate = input('reservation', '');
        $arr    = explode(" - ", $sldate);
        $map    = [];
        $map[]=['del','=',0];
        if (count($arr) == 2) {
            $arrdateone = strtotime($arr[0]);
            $arrdatetwo = strtotime($arr[1] . ' 23:59:59');
            $map[]      = ['a.create_time', 'between', [$arrdateone, $arrdatetwo]];
        }
        //---时间格式

        if (input('mobile', '')!=''){
            $map[] = ['a.mobile', 'like', "%" . input('mobile') . "%"];
        }
        if (input('realname', '')!=''){
            $map[] = ['a.realname', 'like', "%" .  input('realname') . "%"];
        }
        if (input('user_type', '')!=''){
            $map[] = ['a.user_type', '=', input('user_type') ];
        }
        //---筛选结束

        if (input('export', '')=='1'){//导出
            $this->export($map);
        }

        //        每页多少条
        $list_rows=input('list_rows', '');
        if ($list_rows==''){
            $list_rows=config('paginate.list_rows');
        }



        $model = new UsersModel();
        $news       = $model->alias("a")
//            ->field('a.*,b.realname as b_realname,c.realname as c_realname')
                ->with(['followId','sellId'])
//            ->join( 'users b', 'a.follow_id =b.id')
//            ->join( 'users c', 'a.sell_id =c.id')
            ->where($map)
            ->order('a.id desc')
//            ->select();

            ->paginate($list_rows, false, ['query' => get_query()]);
//        foreach ($news as &$value) {
//            //查看地址列表
//            $value['address_list'] = url('UsersAddress/index', ['uid' => $value['id']]);
//            //dump($value);die;
//            //$value['aa'] = url('5555');
//        }
        $page       = $news->render();
        $page       = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)", "<a href='javascript:ajax_page($1);'>$2</a>", $page);
        $data       = $news->items();

        //序号/姓名/头像/手机号/客户类型/状态/来源/归属/购买次数/总金额（元）/余额（元）/收货地址/创建时间/操作
        //表格字段
        $fields = [
            ['title' => 'ID/序号', 'field' => 'id'],
            ['title' => '姓名', 'field' => 'realname'],
            ['title' => '头像', 'field' => 'photo', 'img' => '1'],

            ['title' => '手机号', 'field' => 'mobile'],
            ['title' => '客户类型', 'field' => 'user_type' , 'type' => 'array', 'array' =>$model->user_type_text],
//            ['title' => '状态', 'field' => 'status', 'type' => 'switch', 'url' => url('newsState')],
            ['title' => '状态', 'field' => 'lock', 'type' => 'array',  'array' =>$model->lock_trxt],

            ['title' => '来源', 'field' => 'come_from', 'type' => 'array', 'array' =>$model->come_from_text ],
            ['title' => '开发id', 'field' => 'followId.id'],
            ['title' => '开发姓名', 'field' => 'followId.realname'],
            ['title' => '销售id', 'field' => 'sell_id'],
            ['title' => '销售姓名', 'field' => 'sellId.realname'],
//            ['title' => '归属', 'field' => 'name'],
//            ['title' => '购买次数'],
            ['title' => '总金额（元）', 'field' => 'account' ],
            ['title' => '余额（元）', 'field' => 'account'],
//            ['title' => '收货地址', ],
            ['title' => '用户地址','type' => 'open_window','field' => 'address_list', 'class'=>'blue yf-modal-open'],

            ['title' => '创建时间', 'field' => 'reg_time']
//            ['title' => '创建时间', 'field' => 'reg_time', 'type' => 'date']
        ];
        $pk     = 'id';
        //右侧操作按钮
        $right_action = [
            'edit'   => ['href' => url('edit'), 'is_pop' => 1],
//            'download' => ['title' => '用户地址','is_pop'=>1,'field' => 'address_list','text'=>'用户地址', 'class'=>'blue yf-modal-open'],
            'delete' => url('del'),
        ];
        $order        = '';//排序
        $delall       = [
            ['text'=>'全删','url'=>url('allDel'),'class'=>'btn btn-white btn-yellow btn-sm delall-btn'],
            ['text'=>'分配','url'=> url('allUpdata'),'class'=>'btn btn-white btn-yellow btn-sm allUpdata-btn'],
        ];

        $search       = [
           /*行数*/ ['select', 'list_rows', '', config('page_rows.'),                      $list_rows, '', '', ['is_formgroup' => false], 'class' => ''],

            ['text', 'realname', '',  input('realname'), '', '', 'text', ['placeholder' => '姓名查询', 'is_formgroup' => false], 'search-query'],
            ['text', 'mobile', '',  input('mobile'), '', '', 'text', ['placeholder' => '手机号码', 'is_formgroup' => false], 'search-query'],
            ['select', 'user_type', '', $model->user_type_text, input('user_type',''), '', '', ['is_formgroup' => false, 'default' => '用户类型'], 'ajax_change'],

//            ['daterange', 'reservation', '', $sldate, '', ['is_formgroup' => false, 'placeholder' => '点击选择日期范围'], '', 'height:30px;margin:auto 2px;'],
            ['button', '搜索', ['class' => 'btn btn-purple btn-sm search-query ajax-search-form', 'type' => 'submit', 'icon_l' => 'ace-icon fa fa-search icon-on-right bigger-110']],
                                //导出按钮， class
            ['export', '导出','btn btn-purple btn-sm search-query export-form'],
        ];
        if (!config('yfcmf.lang_switch_on')) {
            unset($search[2]);
        }

        $form         = [
            'href'  => url('newsIndex'),
            'class' => 'form-search',
            'id'    => 'list-filter'
        ];
        //实例化表单类
        $widget = new Widget();
        if (request()->isAjax()) {
            return $widget
                ->form('table', $fields, $pk, $data, $right_action, $page, $order, $delall, 1);
        } else {
            return $widget
                ->addToparea([
                    'add' => ['href' => url('add'), 'is_pop' => 1],
                    'import' => ['href' => url('import'), 'is_pop' => 1]
                ], [], $search, $form)
//                ->setTemplate(Env::get('app_path') . 'common/widget/form/layout.html')
                ->addtable($fields, $pk, $data, $right_action, $page, $order, $delall)
                ->setButton()
                ->fetch();

        }

    }

    /**
     * 添加
     * @throws
     */
    public function add()
    {
       if (request()->isPost()){
           $add_data  =input('');
           $add_data['reg_time']=date('Y-m-d H:i:s');
           $rst             = UsersModel::create($add_data);
           if ($rst) {
               $this->success('添加成功,返回列表页', 'index', ['is_frame' => 1]);
           } else {
               $this->error('添加失败,返回列表页', 'index', ['is_frame' => 1]);
           }
       }
       else{
           $AdminModel=new Admin;
           $UsersModel= new UsersModel();
           // dump($AdminModel->get_admin_name(3));die;
           //实例化表单类
           $widget = new Widget();
           return $widget
//单行文本输入 addText，下拉框 addSelect，多选框 addCheckbox，单图上传 addImage，多图上传 addImages，
//开关 addSwitch，时间 addDate，多行文本框 addTextarea，富文本 addUeditor
               ->addImage('photo', '头像上传', '', '上传前先用PS处理成等比例图片后上传，最后都统一比例')
//            ->addFile('file','excel','','上传模板填充数据后的excel文件,格式不正确会有未知后果')
               ->addSelect('follow_id', '开发', $AdminModel->get_admin_name(4), '','','', ['default' => '选择开发'])
               ->addSelect('sell_id', '销售', $AdminModel->get_admin_name(3), '','','', ['default' => '选择销售'])

               ->addText('mobile', '手机号', '', '', 'required', 'text',['placeholder' => '必填'])
               ->addText('realname', '姓名', '', '', 'required', 'text',['placeholder' => '必填'])
               ->addSelect('user_type', '类型', $UsersModel->user_type_text, '1','','')
               ->addSelect('status', '状态', $UsersModel->lock_trxt, '0','','' )
               ->addSelect('come_from', '来源', $UsersModel->come_from_text, '2','','' )
//            ->addTextarea('address', '文章简介', '', '已限制在100个字以内', '', ['maxlength' => 100, 'autosize' => 1])

               ->setUrl(url('add'))
               ->setAjax('ajaxForm-noJump')
               ->fetch();
       }

    }


    /**
     * 编辑
     * @throws
     */
    public function edit()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误', 'index');
        }

        if (request()->isPost()){
            $data  =input('');
            $rst             = UsersModel::update($data);
            if ($rst !== false) {
                $this->success('修改成功', 'index', ['is_frame' => 1]);
            } else {
                $this->error('修改失败', 'index', ['is_frame' => 1]);
            }
        }
        else{
            $AdminModel=new Admin;
            $UsersModel= new UsersModel();
            $list    = UsersModel::get($id);
            //实例化表单类
            $widget = new Widget();
            return $widget
//单行文本输入 addText，下拉框 addSelect，多选框 addCheckbox，单图上传 addImage，多图上传 addImages，
//开关 addSwitch，时间 addDate，多行文本框 addTextarea，富文本 addUeditor， 设置触发 setTrigger
                ->addText('id', '', $id, '', '', 'hidden')
                ->addImage('photo', '头像上传', $list['photo'], '上传前先用PS处理成等比例图片后上传，最后都统一比例')
                ->addSelect('follow_id', '开发', $AdminModel->get_admin_name(4),  $list['follow_id'],'','', ['default' => '选择开发'])
                ->addSelect('sell_id', '销售', $AdminModel->get_admin_name(3), $list['sell_id'],'','', ['default' => '选择销售'])

                ->addText('mobile', '手机号', $list['mobile'], '', '', 'text')
                ->addText('realname', '姓名', $list['realname'], '', '', 'text')
                ->addSelect('user_type', '类型', $UsersModel->user_type_text, $list['user_type'],'','')
                ->addSelect('status', '状态', $UsersModel->lock_trxt, $list['status'],'','' )
                ->addSelect('come_from', '来源', $UsersModel->come_from_text, $list['come_from'],'','' )
                ->setUrl(url('edit'))
                ->setAjax('ajaxForm-noJump')
                ->fetch();
        }

    }



    /**
     * 删除
     */
    public function del()
    {
        $model = new UsersModel();
        $rst        = $model->where('id', input('id'))->update(['del'=>1]);
        if ($rst !== false) {
            $this->success('删除成功', 'index');
        } else {
            $this->error("删除失败！", 'index');
        }
    }

    /*
     * 批量删除
     */
    function allDel(){
        $ids = input('ids/a');
        $ids=implode(',',$ids);
        $model = new UsersModel();
        $rst        = $model->where('id', 'in',$ids)->update(['del'=>1]);
        if ($rst !== false) {
            $this->success('删除成功', 'index');
        } else {
            $this->error("删除失败！", 'index');
        }
       // $this->success('批量删除成功', 'index');
    }

    /*
     * 批量修改用户销售/开发
     */
    function allUpdata(){
        $ids = input('ids');
       // dump($id);die;
        if (request()->isPost()){
            $data  =[
                'follow_id'=>input('follow_id'),
                'sell_id'=>input('sell_id'),
            ];

            //dump($data);die;

            $rst             = UsersModel::where('id','in',$ids)->update($data);
            if ($rst !== false) {
                $this->success('修改成功', 'index', ['is_frame' => 1]);
            } else {
                $this->error('修改失败', 'index', ['is_frame' => 1]);
            }
        }
        else{
            $AdminModel=new Admin;
            $UsersModel= new UsersModel();
//            $list    = UsersModel::where('id','in',$ids)->select();
//            dump($list);die;
            //实例化表单类
            $widget = new Widget();
            return $widget
//单行文本输入 addText，下拉框 addSelect，多选框 addCheckbox，单图上传 addImage，多图上传 addImages，
//开关 addSwitch，时间 addDate，多行文本框 addTextarea，富文本 addUeditor， 设置触发 setTrigger
                ->addText('ids', '', $ids, '', '', 'hidden')
                ->addSelect('follow_id', '开发', $AdminModel->get_admin_name(4),  '','','', ['default' => '选择开发'])
                ->addSelect('sell_id', '销售', $AdminModel->get_admin_name(3), '','','', ['default' => '选择销售'])

                ->setUrl('allUpdata')
                ->setAjax('ajaxForm-noJump')
                ->fetch();
        }
    }

    function export($map=[]){
        $name='用户';
        //数据
        $model = new UsersModel();
        $modeldata       = $model->alias("a")
//            ->field('a.*,b.realname as b_realname,c.realname as c_realname')
            ->with(['followId','sellId'])
//            ->join( 'users b', 'a.follow_id =b.id')
//            ->join( 'users c', 'a.sell_id =c.id')
            ->where($map)
            ->order('a.id desc')
            ->select();
        //dump($data);die;

        //表头
        $headArr=['ID/序号','姓名','手机号','客户类型','状态','来源','开发id','开发姓名','销售id','销售姓名',
            '余额','加入时间'];
        $data=[];
       $user_type_text= $model->user_type_text;
        $lock_trxt=$model->lock_trxt;
        $come_from_text=$model->come_from_text;
        foreach ($modeldata as $k=>$v){
            $data[$k]=[
                $v['id'],$v['realname'],$v['mobile'],
                $user_type_text[$v['user_type']],
                $lock_trxt[$v['lock']],
                $come_from_text[$v['come_from']],
                $v['followId']['id'],
                $v['followId']['realname'],
                $v['sellId']['id'],
                $v['sellId']['realname'],
                $v['account'],
                $v['reg_time'],
            ];
        }

        $this->export_public($name,$headArr,$data);
       // echo '导出';
    }

    //'导入';
    function import(){
        if (request()->isPost()){
            $file= $this-> upload();

           // $file = input('file');

            if (!$file) {
                $this->error("未上传！");
               // $this->error(303, '缺少file');
            }
            //调用导入excel方法
            $data = $this->importExcel($file);
            unset($data[0]);
            //
            unlink($file);//删除上传的文件

            foreach ($data as $k=>$v){
//                $headArr=['姓名','手机号','客户类型(1=普通用户,2=会员用户,3=加盟商)',
//'状态(0=启用,1=禁用)','来源(1=小程序,2=录入)','开发id','销售id','加入时间'];
                $add_data=[
                    'realname'=>$v[0],
                    'mobile'=>$v[1],
                    'user_type'=>$v[2],
                    'lock'=>$v[3],
                    'come_from'=>$v[4],
                    'follow_id'=>$v[5],
                    'sell_id'=>$v[6],
                    'reg_time'=>date('Y-m-d H:i:s'),
                ];
                UsersModel::create($add_data);
            }
            return $this->success('已导入','index');
//            importExcel
        }
        else{
            return $this->fetch();
        }


    }



    //excel导入摸板
    function excelModel(){
        $name='user_model';


        //表头
        $headArr=['姓名','手机号','客户类型(1=普通用户,2=会员用户,3=加盟商)','状态(0=启用,1=禁用)','来源(1=小程序,2=录入)','开发id','销售id','加入时间'];
        $data=[];

        $this->export_public($name,$headArr,$data);
    }



}